﻿using FineUI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using ZHDJ.BranchCenter.BLL;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Center;
using ZHDJ.WebPage;

namespace ZHDJ.BranchCenter.Module.BranchActivity
{
    public partial class BranchActivityRecordEdit : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }
        #endregion

        #region 页面属性
        public string EditorContent
        {
            get
            {
                string id = GetQueryIntValue("id");
                if (!string.IsNullOrEmpty(id))
                {
                    PartyBranchActivitie article = DB.PartyBranchActivities.Find(id);
                    return article.Record;
                }
                else
                {
                    return string.Empty;
                }
            }
        }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        private void BindData()
        {
            ControlBusiness.ControlBindDataDictionary(ddlThematic, "ZHDJ.BranchActivity.Thematic");
        }

        private void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                PartyBranchActivitie activity = DB.PartyBranchActivities.Find(id);
                if (activity == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }

                txtTitle.Text = activity.Title;
                dpBeginTime.Text = Convert.ToDateTime(activity.BeginTime).ToString("yyyy-MM-dd");
                dpEndTime.Text = Convert.ToDateTime(activity.EndTime).ToString("yyyy-MM-dd");
                txtAddress.Text = activity.Address;
                ddlThematic.SelectedValue = activity.Thematic;
                hdFileId.Text = activity.ImageID;
                HyperLink1.ImageID = activity.ImageID;
                cbIsTop.Checked = activity.Flags == 1;
                cbIsRelease.Checked = activity.Status == 4;

                IQueryable<PartyBranchActivitieMember> q = DB.PartyBranchActivitieMembers.Where(t => t.ActivitieID == id);

                if (q.Count() > 0)
                {
                    StringBuilder sbLoginID = new StringBuilder();
                    StringBuilder sbName = new StringBuilder();

                    foreach (PartyBranchActivitieMember item in q)
                    {
                        sbLoginID.Append(item.LoginID + ",");
                        sbName.Append(ControlBusiness.GetMembersPickerText(item.LoginID) + ",");
                    }

                    ppMember.Value = sbLoginID.ToString().TrimEnd(',');
                    ppMember.Text = sbName.ToString().TrimEnd(',');

                    DataTable dtMember = PartyBranchActivitieMember.GetGridData(id);
                    cblActualMember.DataSource = dtMember;
                    cblActualMember.DataBind();

                    foreach (CheckItem item in cblActualMember.Items)
                    {
                        DataRow[] dataRow = dtMember.Select("LoginID='" + item.Value + "' and Status=2");
                        item.Selected = dataRow.Length > 0;
                    }
                }

                //活动结束
                if (activity.IsEnd == true)
                {
                    btnEndActivity.Hidden = true;
                    ToolbarSeparator2.Hidden = true;
                }

                //如果是根组织
                if (this.BranchID == PartyOrg.QueryTopBranchId())
                {
                    cbIsUp.Hidden = true;
                }
            }
        }
        #endregion

        #region Events

        private void SaveData(bool isEnd)
        {
            string id = GetQueryIntValue("id");
            id = string.IsNullOrEmpty(id) ? StringHelper.NewID : id;
            List<string> joinedMember = new List<string>();
            if (id != "")
            {
                //更新
                PartyBranchActivitie activity = DB.PartyBranchActivities.Find(id);
                if (activity == null)
                {
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }

                DataTable dtMember = PartyBranchActivitieMember.GetGridData(id);

                foreach (CheckItem item in cblActualMember.Items)
                {
                    if (item.Selected)
                    {
                        PartyBranchActivitieMember.UpdateMemberStatus(id, item.Value, 2);
                        joinedMember.Add(item.Value);
                    }
                }
                if (!string.IsNullOrEmpty(hdFileId.Text))
                {
                    activity.ImageID = hdFileId.Text;
                }
                if (cbIsRelease.Checked)
                {
                    activity.Status = 4;
                }
                if (!(bool)activity.IsEnd)
                {
                    activity.IsEnd = isEnd;
                }
                activity.Flags = cbIsTop.Checked ? 1 : 0;
                activity.Record = this.Request.Form["editorValue"];
                activity.ModifyTime = DateTime.Now;
                activity.ModifyBy = CurrentUser.LoginID;

                if (DB.SaveChanges() > 0 && isEnd)
                {
                    //增加积分
                    PartyScoreHelper.Add(() => PartyScoreHelper.AddBranchActivity(joinedMember, activity.BranchID, CurrentUser.LoginID, activity.ID, Convert.ToDateTime(activity.BeginTime).ToString("yyyy-MM-dd")));
                }
            }
        }

        /// <summary>
        /// 保存并关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData(false);

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        /// <summary>
        /// 活动记录并结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEndActivity_Click(object sender, EventArgs e)
        {
            SaveData(true);

            string id = GetQueryIntValue("id");
            PartyBranchActivitie activity = DB.PartyBranchActivities.Find(id);

            //是否推送到上级组织
            if (cbIsUp.Checked)
            {
                PartyBranchActivitie copyActivity = new PartyBranchActivitie();
                copyActivity.ID = StringHelper.NewID;
                copyActivity.Title = activity.Title;
                copyActivity.BranchID = PartyOrg.QueryParentBranchID(activity.BranchID);
                copyActivity.RelationID = activity.BranchID;
                copyActivity.Thematic = activity.Thematic;
                copyActivity.BeginTime = activity.BeginTime;
                copyActivity.EndTime = activity.EndTime;
                copyActivity.Address = activity.Address;
                copyActivity.ImageID = activity.ImageID;
                copyActivity.IsEnd = activity.IsEnd;
                copyActivity.Record = activity.Record;
                copyActivity.Flags = activity.Flags;
                copyActivity.Status = activity.Status;
                copyActivity.CreateBy = activity.CreateBy;
                copyActivity.CreateTime = activity.CreateTime;
                copyActivity.ModifyBy = activity.ModifyBy;
                copyActivity.ModifyTime = activity.ModifyTime;

                DB.PartyBranchActivities.Add(copyActivity);
                DB.SaveChanges();
            }

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void rblOperate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.rblOperate.SelectedValue.Equals("0"))
            {
                foreach (CheckItem item in cblActualMember.Items)
                {
                    item.Selected = true;
                }
            }
            else if (this.rblOperate.SelectedValue.Equals("1"))
            {
                foreach (CheckItem item in cblActualMember.Items)
                {
                    item.Selected = false;
                }
            }
            else if (this.rblOperate.SelectedValue.Equals("2"))
            {
                foreach (CheckItem item in cblActualMember.Items)
                {
                    if (item.Selected)
                    {
                        item.Selected = false;
                    }
                    else
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID);
            if (rs.IsSuccess)
            {
                hdFileId.Text = rs.FileID;
                HyperLink1.ImageID = rs.FileID;
            }
        }
        #endregion
    }
}